package dataAccess;

import java.util.*;
import java.sql.*;

import dataAccess.Connector;
import dataAccess.DALException;
import dataAccess.LuckyCardDTO;

public class MySQLLuckyCardDAO implements LuckyCardDAO{

	public LuckyCardDTO getLuckyCard(int cardID) throws DALException {
		ResultSet rs = Connector
				.doQuery("SELECT * FROM Luckycard WHERE Card_ID = " + cardID);
		try {
			if (!rs.first())
				throw new DALException("Kortet " + cardID + " findes ikke.");
			return new LuckyCardDTO(rs.getInt("Card_ID"),
					rs.getString("Description"), rs.getString("Command"),
					rs.getInt("Bonus"), rs.getBoolean("Jailcard"));
		} catch (SQLException e) {
			throw new DALException(e);
		}
	}

	public List<LuckyCardDTO> getLuckyCardList() throws DALException {
		List<LuckyCardDTO> data = new ArrayList<LuckyCardDTO>();
		ResultSet rs = Connector.doQuery("SELECT * FROM LuckyCard");
		try {
			while (rs.next()) {
				data.add(new LuckyCardDTO(rs.getInt("Card_ID"), rs
						.getString("Description"), rs.getString("Command"), rs
						.getInt("Bonus"), rs.getBoolean("Jailcard")));
			}
		} catch (SQLException e) {
			throw new DALException(e);
		}
		return data;
	}

	public void createLuckyCard(LuckyCardDTO card) throws DALException {
		Connector.doUpdate("INSERT INTO Luckycard VALUES (" + card.getCardID()
				+ ", '" + card.getDescription() + "', '" + card.getCommand()
				+ "', " + card.getBonus() + ", " + card.getJailcard() + ");");
	}
	
	public void createLuckyCardList(List<LuckyCardDTO> cards)
			throws DALException {
		for (int i = 0; i < cards.size(); i++) {
			createLuckyCard(cards.get(i));
		}
	}

	public void updateLuckyCard(LuckyCardDTO card) throws DALException {
		Connector.doUpdate("UPDATE Luckycard SET Description = '"
				+ card.getDescription() + "', Command = '" + card.getCommand()
				+ "', Bonus = " + card.getBonus() + ", Jailcard = "
				+ card.getJailcard() + " WHERE Card_ID = " + card.getCardID()
				+ ";");
	}
	
	public void updateLuckyCardList(List<LuckyCardDTO> cards)
			throws DALException {
		for (int i = 0; i < cards.size(); i++) {
			Connector.doUpdate("UPDATE Luckycard SET Description = '"
					+ cards.get(i).getDescription() + "' , Command = '"
					+ cards.get(i).getCommand() + "', Bonus = "
					+ cards.get(i).getBonus() + ", Jailcard = "
					+ cards.get(i).getJailcard() + " WHERE Card_ID = " + (i + 1)
					+ ";");
		}
	}
	
	public void deleteLuckyCard(int cardID) throws DALException {
		Connector.doUpdate("DELETE FROM Luckycard WHERE Card_ID = " + cardID);
	}
}
